//
//  LibraryDetailViewController.m
//  觅影
//
//  Created by Zeus on 16/4/8.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "LibraryDetailViewController.h"
#import "MovieDatasHeaderView.h"
#import "WatchFocusView.h"
#import "TagViewTableViewCell.h"
#import "MovieIntroTableViewCell.h"
#import "SameFilmCommentsTableViewCell.h"
#import "HotModel.h"
#import "focusModel.h"
#import "FilmCommentModel.h"
#import "FilmIntroModel.h"
#import "StagePhotoViewController.h"

@interface LibraryDetailViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSMutableDictionary *dic2;
@property (nonatomic, strong) NSMutableArray *rowArray;   // 评论数组
@property (nonatomic, strong) UITableViewCell *myCell;
@property (nonatomic, strong) NSMutableArray *focusTagsArray;  // 标签数组
@property (nonatomic, strong) HotModel *detailModel;
@property (nonatomic, strong) focusModel *focusModel;
@property (nonatomic, strong) FilmIntroModel *introModel;
@property (nonatomic, strong) NSMutableArray *commentTagsArray;  // 评论标签数组
@property (weak, nonatomic) IBOutlet UITableView *filmTableView;
@property (nonatomic, strong) MovieDatasHeaderView *headerView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSMutableArray *bigArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSMutableArray *moreCommentArr;
@property (nonatomic, strong) FMDatabase *db;
@end

@implementation LibraryDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"电影详情";
    
    // 创建数据库路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"LibraryDetail.db"];
    self.db = [FMDatabase databaseWithPath:path];
    if (![self.db open]) {
        NSLog(@"不能打开数据库");
    }
    //创建表
    [self.db executeUpdate:@"CREATE TABLE WantFilm (Poster text, Title text, FilmStyle text, FilmId text)"];
    
    // 给大数组设置占位元素 以此判断是否拥有请求好的数据
    NSArray *cell1 = @[];
    NSArray *cell2 = @[];
    NSArray *cell3 = @[];
    self.bigArray = [NSMutableArray arrayWithObjects:cell1,cell2,cell3, nil];

    self.filmTableView.delegate = self;
    self.filmTableView.dataSource = self;
    // 告诉系统 采用系统自动返回的高度
    self.filmTableView.rowHeight = UITableViewAutomaticDimension;
    // 预设高度
    self.filmTableView.estimatedRowHeight = 10;
    [self.filmTableView registerNib:[UINib nibWithNibName:@"TagViewTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.filmTableView registerNib:[UINib nibWithNibName:@"MovieIntroTableViewCell" bundle:nil] forCellReuseIdentifier:@"intro"];
    [self.filmTableView registerNib:[UINib nibWithNibName:@"SameFilmCommentsTableViewCell" bundle:nil] forCellReuseIdentifier:@"comment"];
    self.headerView = [[MovieDatasHeaderView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 250 + 40 + 45)];
    self.filmTableView.tableHeaderView = _headerView;
    self.rowArray = [NSMutableArray array];
    self.focusTagsArray = [NSMutableArray array];
    self.modelArray = [NSMutableArray array];
    self.moreCommentArr = [NSMutableArray array];
    // tag 的网络请求
    [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/tag_list?pos=2&movie_id=%@",_movieId] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        _dic2 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // focus 的网络请求
        [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/focus_list?pos=2&movie_id=%@",_movieId] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
            NSMutableArray *focusArray =[focusModel modelConfigureJsonDic:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] jsonDic2:_dic2];
            self.focusTagsArray = focusArray;
            if (_focusTagsArray.count != 0) {
                self.bigArray[0] = _focusTagsArray;
            }
            dispatch_async(dispatch_get_main_queue(),^{
                [self.filmTableView reloadData];
            });
        } error:nil];
    } error:nil];
    
    // 电影详情的网络请求
    [self sendRequest:_movieId];

    // 评论的网络请求
    [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/list_by_movie?movie_id=%@&page=1&page_size=10", _movieId] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        FilmCommentModel *film = [[FilmCommentModel alloc]init];
        NSMutableArray *commentArray = [film modelConfigureJsonDic:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
        self.rowArray = commentArray;
        if (_rowArray.count != 0) {
            self.bigArray[2] = _rowArray;
            _page++;
        }
        dispatch_async(dispatch_get_main_queue(),^{
            [self.filmTableView reloadData];
        });
    } error:nil];
    self.filmTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self reloadMoreCommentsData];
    }];
}
# pragma mark --- 设置表头 ---
- (void)setTheHeaderView{
    [_headerView.tap addTarget:self action:@selector(tapAction:)];
    [_headerView.picView sd_setImageWithURL:[NSURL URLWithString:_introModel.poster]];
    if (_introModel.poster.length == 0) {
        _headerView.tap.enabled = NO;
    }
    _headerView.titleLabel.text = _introModel.title;
    
    // 从数据库中抓取数据,判断是否已加入想看
    FMResultSet *rs = [self.db executeQuery:@"SELECT * FROM WantFilm"];
    while ([rs next]) {
        NSString *filmId = [rs stringForColumn:@"FilmId"];
        if ([filmId isEqualToString:_movieId]) {
            self.headerView.want_watch.enabled = NO;
            self.headerView.want_watch.backgroundColor = [UIColor lightGrayColor];
        }
    }
    [_headerView.want_watch addTarget:self action:@selector(addWantWatchList:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark --- 点击想看按钮 ---
- (void)addWantWatchList:(UIButton *)wantButton
{
    // 将点击过的想看写入数据库
    [self.db executeUpdate:@"INSERT INTO WantFilm (Poster, Title, FilmStyle, FilmId) VALUES(?,?,?,?)",_introModel.poster, _introModel.title, _introModel.filmtype, _movieId];
    wantButton.enabled = NO;
    wantButton.backgroundColor = [UIColor lightGrayColor];
    
}
- (void)tapAction:(UITapGestureRecognizer *)tap{
    StagePhotoViewController *stagePhotoVc = [[StagePhotoViewController alloc]init];
    stagePhotoVc.movieId = _movieId;
    [self.navigationController pushViewController:stagePhotoVc animated:YES];
}
/***************************** paw 解码********************************/
- (void)sendRequest:(NSString *)movieId
{
    /* Configure session, choose between:
     * defaultSessionConfiguration
     * ephemeralSessionConfiguration
     * backgroundSessionConfigurationWithIdentifier:
     And set session-wide properties, such as: HTTPAdditionalHeaders,
     HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
     */
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    /* Create the Request:
     My API (GET http://static.v6v7.com/pingping_japi/movie/simple/)
     */
    NSURL* URL = [NSURL URLWithString:@"http://static.v6v7.com/pingping_japi/movie/simple/"];
    NSDictionary* URLParams = @{
                                @"movieId": _movieId,
                                };
    URL = NSURLByAppendingQueryParameters(URL, URLParams);
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"GET";
    
    // Headers
    [request addValue:@" JSESSIONID=B5D98C918B8C3C592B0CCB54238A9088; sessionid=p6r84oeanc2309sk4j1is2baxdq2q55b" forHTTPHeaderField:@"Cookie"];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    // Form URL-Encoded Body
    NSDictionary* bodyParameters = @{
                                     };
    request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
    
    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            // Success
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            self.introModel = [FilmIntroModel modelConfigureJsonDic:dic];
            
            [self.modelArray addObject:_introModel];
            self.bigArray[1] = _modelArray;
            dispatch_async(dispatch_get_main_queue(),^{
                [self.filmTableView reloadData];
                [self setTheHeaderView];
            });
        }
        else {
            // Failure
        }
    }];
    [task resume];
}
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
    NSMutableArray* parts = [NSMutableArray array];
    [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        NSString *part = [NSString stringWithFormat: @"%@=%@",
                          [key stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]],
                          [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]
                          ];
        [parts addObject:part];
    }];
    return [parts componentsJoinedByString: @"&"];
}

static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
    NSString* URLString = [NSString stringWithFormat:@"%@?%@",
                           [URL absoluteString],
                           NSStringFromQueryParameters(queryParameters)
                           ];
    return [NSURL URLWithString:URLString];
}
# pragma mark --- 上拉加载更多评论 ---
- (void)reloadMoreCommentsData{
    _page++;
    NSLog(@"page %ld, id %@", _page, _movieId);
    if (![self.bigArray[2] isEqualToArray:@[]] && _page != 1) {
        [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/list_by_movie?movie_id=%@&page=%ld&page_size=10", _movieId, _page] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
            FilmCommentModel *film = [[FilmCommentModel alloc]init];
            NSMutableArray *commentArray = [film modelConfigureJsonDic:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
            if (commentArray.count != 0) {
                NSMutableArray *array = [NSMutableArray arrayWithArray:self.rowArray];
                for (FilmCommentModel *film in commentArray) {
                    [array addObject:film];
                }
                self.bigArray[2] = array;
                dispatch_async(dispatch_get_main_queue(),^{
                    [self.filmTableView reloadData];
                    [self.filmTableView.mj_footer endRefreshing];
                });
            }
        } error:nil];
    }
    if (_page == 1) {
        dispatch_async(dispatch_get_main_queue(),^{
            [self.filmTableView.mj_footer endRefreshing];
        });
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([_bigArray[section] isEqualToArray:@[]]) {
        return 0;
    }else{
        if (section == 2) {
            NSArray *array = self.bigArray[section];
            return [array count];
        }
        else{
            return 1;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        WatchFocusView *focusView = [[WatchFocusView alloc]initWithFrame:CGRectMake(0, 5, KWIDTH - 10, 0)];
        [focusView setTagWithTagArray:_focusTagsArray];
        focusView.singleColor = [UIColor colorWithRed:152/255.0 green:167/255.0 blue:232/255.0 alpha:1];
        TagViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.tagsViewHeight.constant = focusView.frame.size.height;
        [cell.tagsView addSubview:focusView];
        self.myCell = cell;
    }
    else if (indexPath.section == 1){
        MovieIntroTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"intro" forIndexPath:indexPath];
        cell.actors.text = [NSString stringWithFormat:@"主演：%@", _introModel.actors];
        cell.director.text = [NSString stringWithFormat:@"导演：%@",_introModel.directors];
        cell.showTime.text = [NSString stringWithFormat:@"上映时间：%@",_introModel.pubdate];
        cell.type.text = [NSString stringWithFormat:@"类型：%@", _introModel.filmtype];
        cell.language.text = [NSString stringWithFormat:@"语言：%@", _introModel.language];
        if (_introModel.nickname.length != 0) {
            cell.alias.text = [NSString stringWithFormat:@"别名：%@", _introModel.nickname];
        }
        else{
            cell.alias.text = [NSString stringWithFormat:@"别名：%@", _introModel.title];
        }
        if (_introModel.douban_score.length > 0) {
            cell.score.text = [NSString stringWithFormat:@"评分：%@", _introModel.douban_score];
        }
        else if (_introModel.imdb_score.length > 0){
            cell.score.text = [NSString stringWithFormat:@"评分：%@", _introModel.imdb_score];
        }
        else{
            cell.score.frame = CGRectMake(0, 0, 0, 0);
        }
        cell.filmLength.text = [NSString stringWithFormat:@"片长：%@", _introModel.mins];
        if (_introModel.area.length > 0) {
            cell.area.text = [NSString stringWithFormat:@"地区：%@", _introModel.area];
        }
        else{
            cell.area.frame = CGRectMake(0, 0, 0, 0);
        }
        cell.comments.text = [NSString stringWithFormat:@"%@", _introModel.plots];
        self.myCell = cell;
    }
    else if (indexPath.section == 2){
        SameFilmCommentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"comment" forIndexPath:indexPath];
        FilmCommentModel *commentModel = [[FilmCommentModel alloc]init];
        commentModel = self.bigArray[2][indexPath.row];
        [cell.iconImage sd_setImageWithURL:[NSURL URLWithString:commentModel.header]];
        cell.userName.text = commentModel.username;
        WatchFocusView *focusView = [[WatchFocusView alloc]initWithFrame:CGRectMake(0, 5, KWIDTH - 10, 0)];
        [focusView setTagWithTagArray:commentModel.focusesArray];
        [cell cellTagViewHeight:focusView.frame.size.height + 10];
        if (cell.tagView.subviews.count != 0) {
            [cell.tagView.subviews[0] removeFromSuperview];
        }
        [cell.tagView addSubview:focusView];
        cell.comments.text = commentModel.message;
        cell.goodReply.text = [NSString stringWithFormat:@"%@个赞，%@个回复", commentModel.zan_num, commentModel.reply_num];
        if (![commentModel.score isEqual:@0]) {
            NSInteger score = [commentModel.score integerValue];
            NSMutableString *level = [NSMutableString string];
            for (int i = 0; i < score - 1; i ++) {
                [level appendString:@"🌟"];
            }
            cell.levelScore.text = level;
        }
        self.myCell = cell;
    }
    self.myCell.selectionStyle = UITableViewCellSelectionStyleNone;
    return self.myCell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
